<template>
  <view class="detail-page">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="back-btn" @click="navigateBack">
        <!-- <uni-icons type="left" size="24" color="#333"></uni-icons> -->
		<u-icon name="arrow-left" size="40" color="#333"></u-icon>
      </view>
      <view class="title">资讯详情</view>
      <view class="operate-btn" @click="showActionSheet">
        <!-- <uni-icons type="more" size="24" color="#333"></uni-icons> -->
		<u-icon name="more-dot-fill" color="#333"></u-icon>
      </view>
    </view>

    <!-- 文章详情布局 -->
    <view class="article-detail" v-if="newsData.type === 'article'">
      <!-- 文章标题 -->
      <view class="article-title">
        {{ newsData.title }}
      </view>

      <!-- 文章信息 -->
      <view class="article-info">
        <text class="article-source">{{ newsData.area }}</text>
        <text class="article-time">{{ newsData.publishTime }}</text>
        <text class="article-read">阅读 {{ newsData.views }}</text>
      </view>

      <!-- 文章图片 -->
      <view class="article-images" v-if="newsData.images && newsData.images.length > 0">
        <image 
          :src="img" 
          mode="widthFix"
          class="article-img"
          :alt="newsData.title"
          v-for="(img, index) in newsData.images" 
          :key="index"
          @click="previewImage(index)"
        ></image>
      </view>

      <!-- 文章内容 -->
      <view class="article-content">
        <rich-text :nodes="newsData.content"></rich-text>
      </view>

      <!-- 文章作者信息 -->
      <view class="author-info" v-if="newsData.author">
        <image 
          :src="newsData.author.avatar || '/static/carbon-fiber.png'" 
          mode="aspectFill"
          class="author-avatar"
          :alt="newsData.author.name"
        ></image>
        <view class="author-detail">
          <text class="author-name">{{ newsData.author.name }}</text>
          <text class="author-desc">{{ newsData.author.desc || '资深作者' }}</text>
        </view>
        <button class="follow-btn" :class="{ followed: newsData.author.isFollowed }" @click="toggleFollow">
          {{ newsData.author.isFollowed ? '已关注' : '关注' }}
        </button>
      </view>
    </view>

    <!-- 微头条详情布局 -->
    <view class="micro-detail" v-if="newsData.type === 'micro'">
      <!-- 作者信息 -->
      <view class="micro-author">
        <image 
          :src="newsData.author.avatar || '/static/carbon-fiber.png'" 
          mode="aspectFill"
          class="micro-avatar"
          :alt="newsData.author.name"
        ></image>
        <view class="micro-author-info">
          <text class="micro-author-name">{{ newsData.author.name }}</text>
          <text class="micro-publish-time">{{ newsData.publishTime }}</text>
        </view>
        <button class="follow-btn" :class="{ followed: newsData.author.isFollowed }" @click="toggleFollow">
          {{ newsData.author.isFollowed ? '已关注' : '关注' }}
        </button>
      </view>

      <!-- 微头条内容 -->
      <view class="micro-content">
        <text class="micro-text">{{ newsData.content }}</text>
        
        <!-- 微头条图片 -->
        <view class="micro-images" v-if="newsData.images && newsData.images.length > 0">
          <view class="image-grid">
            <image 
              :src="img" 
              mode="aspectFill"
              class="micro-img"
              v-for="(img, index) in newsData.images" 
              :key="index"
              @click="previewImage(index)"
              :style="{width: getImageWidth(newsData.images.length)}"
            ></image>
          </view>
        </view>
      </view>

      <!-- 微头条数据统计 -->
      <view class="micro-stats">
        <text class="publish-place">{{ newsData.area }}</text>
        <text class="read-count">阅读 {{ newsData.views }}</text>
      </view>
    </view>

    <!-- 互动工具栏 -->
    <view class="interactive-bar">
      <view class="interactive-btn" @click="handleLike">
        <!-- <uni-icons 
          type="heart" 
          size="26" 
          :color="isLiked ? '#ff4d4f' : '#999'" 
          :fill="isLiked ? '#ff4d4f' : 'none'"
          class="interactive-icon"
        ></uni-icons> -->
		<u-icon name="heart" size="26" :color="isLiked ? '#ff4d4f' : '#999'" ></u-icon>
        <text class="interactive-text" :class="{ liked: isLiked }">{{ isLiked ? '已赞' : '点赞' }}</text>
      </view>
      
      <view class="interactive-btn" >
        <!-- <uni-icons type="chatbubble" size="26" color="#999" class="interactive-icon"></uni-icons> -->
		<u-icon name="chat" size="26" color="#999"></u-icon>
        <text class="interactive-text">评论</text>
        <text class="comment-count" v-if="newsData.commentCount > 0">{{ newsData.commentCount }}</text>
      </view>
      
      <view class="interactive-btn" @click="handleShare">
        <!-- <uni-icons type="share" size="26" color="#999" class="interactive-icon"></uni-icons> -->
		<u-icon name="share" size="26"  ></u-icon>
        <text class="interactive-text">分享</text>
      </view>
      
      <view class="interactive-btn" @click="handleCollect">
       <!-- <uni-icons 
          type="star" 
          size="26" 
          :color="isCollected ? '#ffb800' : '#999'" 
          :fill="isCollected ? '#ffb800' : 'none'"
          class="interactive-icon"
        ></uni-icons> -->
		<u-icon name="star" size="26" :color="isCollected ? '#ffb800' : '#999'" ></u-icon>
        <text class="interactive-text" :class="{ collected: isCollected }">{{ isCollected ? '已收藏' : '收藏' }}</text>
      </view>
    </view>

    <!-- 评论区 -->
    <view class="comments-section" ref="commentsRef">
      <view class="comments-header">
        <text class="comments-title">评论 ({{ newsData.commentCount }})</text>
		
        <text class="sort-text" @click="toggleSort">
          {{ sortByHot ? '按热度' : '按时间' }}
          <!-- <uni-icons type="arrow-down" size="18" color="#999"></uni-icons> -->
        </text>
		<u-icon name="arrow-down" size="26" color="#999"></u-icon>
      </view>

      <!-- 发表评论 -->
      <view class="comment-input-section">
        <image 
          src="/static/carbon-fiber.png" 
          mode="aspectFill"
          class="user-avatar"
          alt="用户头像"
        ></image>
        <input 
          type="text" 
          placeholder="写下你的评论..." 
          class="comment-input"
          v-model="newCommentContent"
          @focus="hideBottomBar"
          @blur="showBottomBar"
        />
        <button 
          class="send-btn" 
          @click="submitComment"
          :disabled="!newCommentContent.trim()"
        >
          发送
        </button>
      </view>

      <!-- 评论列表 -->
      <view class="comments-list">
        <view 
          class="comment-item" 
          v-for="(comment, index) in filteredComments" 
          :key="comment.id"
        >
          <image 
            :src="comment.user.avatar || '/static/carbon-fiber.png'" 
            mode="aspectFill"
            class="comment-avatar"
            :alt="comment.user.userName"
          ></image>
          
          <view class="comment-content">
            <view class="comment-header">
              <text class="comment-username">{{ comment.user.userName }}</text>
              <text class="comment-time">{{ formatCommentTime(comment.time) }}</text>
            </view>
            
            <text class="comment-text">{{ comment.content }}</text>
            
            <view class="comment-actions">
              <view class="action-item" @click="handleCommentLike(comment)">
                <!-- <uni-icons 
                  type="heart" 
                  size="20" 
                  :color="comment.isLiked ? '#ff4d4f' : '#999'" 
                  :fill="comment.isLiked ? '#ff4d4f' : 'none'"
                ></uni-icons> -->
				<u-icon name="heart" size="26" :color="comment.isLiked ? '#ff4d4f' : '#999'" ></u-icon>
                <text class="action-text"> {{ comment.likeCount > 0 ? comment.likeCount : '' }}</text>
              </view>
              
              <view class="action-item" @click="replyToComment(comment)">
                <!-- <uni-icons type="chatbubble" size="20" color="#999"></uni-icons> -->
				<u-icon name="chat" size="26"></u-icon>
                <text class="action-text">回复</text>
              </view>
            </view>
            
            <!-- 回复列表 -->
            <view class="replies-list" v-if="comment.replies && comment.replies.length > 0">
              <view 
                class="reply-item" 
                v-for="(reply, rIndex) in comment.replies" 
                :key="rIndex"
              >
                <text class="reply-username">{{ reply.user.name }}</text>
                <text class="reply-to" v-if="reply.toUser"> 回复 {{ reply.toUser.name }}</text>
                <text class="reply-content">：{{ reply.content }}</text>
                
                <view class="reply-actions">
                  <view class="reply-action" @click="handleReplyLike(comment, reply)">
                   <!-- <uni-icons 
                      type="heart" 
                      size="18" 
                      :color="reply.isLiked ? '#ff4d4f' : '#999'" 
                      :fill="reply.isLiked ? '#ff4d4f' : 'none'"
                    ></uni-icons> -->
					<u-icon name="heart" size="26" :color="reply.isLiked ? '#ff4d4f' : '#999'" ></u-icon>
                    <text class="reply-action-text">{{ reply.likeCount > 0 ? reply.likeCount : '' }}</text>
                  </view>
                  
                  <view class="reply-action" @click="replyToReply(comment, reply)">
                    <text class="reply-action-text">回复</text>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 回复输入框 -->
            <view class="reply-input-section" v-if="comment.showReplyInput">
              <input 
                type="text" 
                :placeholder="comment.replyingTo ? '回复 @' + comment.replyingTo.name + '...' : '写下你的回复...'" 
                class="reply-input"
                v-model="comment.replyContent"
                @blur="cancelReply(comment)"
                @confirm="submitReply(comment)"
              />
              <button class="reply-send-btn" @click="submitReply(comment)">发送</button>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多评论 -->
      <!-- <view class="load-more-comments" v-if="showLoadMoreComments">
        <uni-loading-icon size="24" color="#1677FF"></uni-loading-icon>
        <text class="load-more-text" @click="loadMoreComments">加载更多评论</text>
      </view> -->
	  <u-loadmore :status="status" @loadmore="loadMoreComments" fontSize="25"/>
    </view>

    <!-- 底部操作栏 -->
<!--    <view class="bottom-bar" :class="{ hidden: bottomBarHidden }">
      <button class="comment-btn" @click="focusCommentInput">
        <uni-icons type="chatbubble" size="24" color="#666" class="btn-icon"></uni-icons>
        <input 
          type="text" 
          placeholder="写下你的评论..." 
          class="comment-input" 
          v-model="newCommentContent"
          @focus="hideBottomBar"
        />
      </button>
      <button class="share-btn" @click="handleShare">
        <uni-icons type="share" size="24" color="#fff" class="btn-icon"></uni-icons>
        分享
      </button>
    </view>  -->
  </view>
</template>

<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {
      newsId: '',
      newsData: {author:{name:'',avatar:'',isFollowed:false}},
      isLiked: false,
      isCollected: false,
      newCommentContent: '',
      comments: [],
      sortByHot: false,
      showLoadMoreComments: false,
      commentPage: 1,
      commentPageSize: 10,
      hasMoreComments: true,
      bottomBarHidden: false,
      commentsRef: null,
	  status:'loadmore',
	  authorId:'',
    };
  },
  
  computed: {
	  
	 ...mapState(['userInfo', "appProperties"]),
	  
    // 根据排序方式过滤评论
    filteredComments() {
      return [...this.comments].sort((a, b) => {
        if (this.sortByHot) {
          // 按热度排序（点赞数降序）
          return b.likeCount - a.likeCount;
        } else {
          // 按时间排序（最新的在前）
          return new Date(b.time) - new Date(a.time);
        }
      });
    }
  },
  
  onLoad(options) {
    // 获取资讯ID
    this.newsId = options.id;
	this.newsData.type = options.type
	this.newsData.title = options.title
	this.newsData.publishTime = options.time
	this.newsData.commentCount = options.comments
	this.newsData.images = options.image?JSON.parse(options.image):[];
	this.newsData.author.name = options.author
	this.newsData.author.avatar = options.avatar
	this.newsData.content = options.content
	this.newsData.views = options.views
	this.newsData.area = options.area?options.area:'IP未知'
	this.authorId = options.authorId
    // 获取资讯详情
    this.fetchNewsDetail();
    // 获取评论
    this.fetchComments();
	//阅读量
	this.newsView();
	//是否关注
	this.isAttention();
  },
  
  onReady() {
    // 保存浏览记录
    this.saveToHistory();
  },
  
  methods: {
    // 获取资讯详情
    fetchNewsDetail() {
      // 模拟从服务器获取数据
      setTimeout(() => {
        // 随机模拟文章或微头条
        const isArticle = this.newsData.type =='article'?true:false;
        
        if (isArticle) {
          // 文章类型数据
          this.newsData = {
            id: this.newsId,
            type: this.newsData.type,
            title: this.newsData.title,
            source: '科技前沿',
            publishTime: this.newsData.publishTime,
            commentCount: this.newsData.commentCount,
            images: this.newsData.images,
            content: this.newsData.content,
			views:this.newsData.views,
			area:this.newsData.area,
            author: {
              name: this.newsData.author.name,
              avatar: this.newsData.author.avatar?this.newsData.author.avatar:'/static/carbon-fiber.png',
              desc: '科技专栏作家，专注AI领域报道',
              isFollowed: this.newsData.author.isFollowed
            }
          };
        } else {
          // 微头条类型数据
          this.newsData = {
            id: this.newsId,
            type: this.newsData.type,
            source: '北京',
            publishTime: this.newsData.publishTime,
            commentCount: this.newsData.commentCount,
            content: this.newsData.content,
            images: this.newsData.images,
			views:this.newsData.views,
			area:this.newsData.area,
            author: {
              name: this.newsData.author.name,
              avatar: this.newsData.author.avatar?this.newsData.author.avatar:'/static/carbon-fiber.png',
              isFollowed: this.newsData.author.isFollowed
            }
          };
        }
        
        
        // this.isLiked = Math.random() > 0.7;
        this.isCollected = Math.random() > 0.8;
        
        // 设置页面标题
        uni.setNavigationBarTitle({
          title: this.newsData.title
        });
      }, 500);
	  // 随机模拟点赞和收藏状态
	  this.targetIsLiked(this.newsId,0);
    },
    
    // 获取评论列表
    fetchComments() {
		this.status = "loading"
       // if (!this.hasMoreComments || this.showLoadMoreComments) return;
      
      // this.showLoadMoreComments = true;
	  const newComments = [];
	  const totalComments = this.commentPage === 1 ? this.newsData.commentCount : this.commentPageSize;
	  const params = {
	    pageNum:  this.commentPage, // 重置时从第1页开始
	    pageSize: this.commentPageSize,
	    newsId: this.newsId , 
	    sortByHot: this.sortByHot
	  };
	  this.$request('api/v1/newComments', 'get',params).then(result => {
		  console.log(result.data)
		  this.newComments = result.data.comments
		  this.comments = [...this.comments, ...this.newComments];
		  this.newsData.commentCount = result.data.total
	  	
	  });
	  
	  // this.showLoadMoreComments = false;
	  // 模拟评论加载完毕
	  if (this.commentPage >= (this.newsData.commentCount/this.commentPageSize)) {
	    // this.hasMoreComments = false;
		this.status = "nomore"
	  }else{
		this.status = "loadmore"  
	  }
 
    },
    
    // 返回上一页
    navigateBack() {
     uni.navigateBack({
       delta: 1, // 返回的页面层级，默认为1
       success: function(res) {
         console.log('成功返回上一页');
       },
       fail: function(err) {
         console.error('返回失败', err);
       }
     });

    },
    
    // 预览图片
    previewImage(current) {
      uni.previewImage({
        current: current,
        urls: this.newsData.images
      });
    },
    
    // 处理点赞
    handleLike() {
		const params = {'userId':this.userInfo.appUserId}
		this.$request(`api/v1/${this.newsId}/newslike?userId=${this.userInfo.appUserId}`, 'post').then(result => {
				  if(result.code==200){
					  this.isLiked = !this.isLiked;
					  // 实际项目中应调用API更新点赞状态
					  uni.showToast({
					    title: this.isLiked ? '点赞成功' : '取消点赞',
					    icon: 'none',
					    duration: 1500
					  });
				  }else{
					  uni.showToast({
					    title: '点赞失败',
					    icon: 'none',
					    duration: 1500
					  });
				  }
				  
			  	
			  });
      
    },
    
    // 处理收藏
    handleCollect() {
      this.isCollected = !this.isCollected;
      // 实际项目中应调用API更新收藏状态
      uni.showToast({
        title: this.isCollected ? '收藏成功' : '取消收藏',
        icon: 'none',
        duration: 1500
      });
    },
    
    // 处理分享
    handleShare() {
      uni.showActionSheet({
        itemList: ['分享给微信好友', '分享到朋友圈', '分享到QQ', '分享到微博'],
        success: (res) => {
          console.log('选择了第' + (res.tapIndex + 1) + '个分享渠道');
          uni.showToast({
            title: '分享成功',
            icon: 'none'
          });
        }
      });
    },
    
    // 显示更多操作
    showActionSheet() {
      uni.showActionSheet({
        itemList: ['举报'],//['举报', '字体大小', '夜间模式'],
        success: (res) => {
          switch(res.tapIndex) {
            case 0:
              this.handleReport();
              break;
            case 1:
              this.adjustFontSize();
              break;
            case 2:
              this.toggleNightMode();
              break;
          }
        }
      });
    },
    
    // 举报功能
    handleReport() {
      uni.showModal({
        title: '举报',
        content: '请选择举报原因',
        showCancel: true,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '举报已提交',
              icon: 'none'
            });
          }
        }
      });
    },
    
    // 调整字体大小
    adjustFontSize() {
      uni.showToast({
        title: '字体大小调整功能开发中',
        icon: 'none'
      });
    },
    
    // 切换夜间模式
    toggleNightMode() {
      uni.showToast({
        title: '夜间模式切换功能开发中',
        icon: 'none'
      });
    },
    
    // 关注/取消关注作者
    toggleFollow() {
		
      if (this.newsData.author&&this.userInfo) {
		const param = {'fansId':this.userInfo.appUserId,'concernId':this.authorId}
		this.$request(`api/v1/dealAttention`, 'POST',param).then(result => {
			if (result.code==200) {
			  // this.newsView();
			  this.newsData.author.isFollowed = !this.newsData.author.isFollowed;
			  uni.showToast({
			    title: this.newsData.author.isFollowed ? '关注成功' : '已取消关注',
			    icon: 'none'
			  });
			}   
			
		});  
		  
		  
		
      }
    },
    
    // 格式化微头条时间
    formatMicroTime(timeStr) {
      try {
        const publishTime = new Date(timeStr);
        const now = new Date();
        const diffMs = now - publishTime;
        const diffMin = Math.floor(diffMs / 60000);
        const diffHour = Math.floor(diffMin / 60);
        const diffDay = Math.floor(diffHour / 24);
        
        if (diffMin < 1) {
          return '刚刚';
        } else if (diffMin < 60) {
          return `${diffMin}分钟前`;
        } else if (diffHour < 24) {
          return `${diffHour}小时前`;
        } else if (diffDay < 7) {
          return `${diffDay}天前`;
        } else {
          const month = publishTime.getMonth() + 1;
          const day = publishTime.getDate();
          return `${month}月${day}日`;
        }
      } catch (e) {
        return '未知时间';
      }
    },
    
    // 根据图片数量计算微头条图片宽度
    getImageWidth(count) {
      if (count === 1) {
        return '100%';
      } else if (count === 2) {
        return '48%';
      } else {
        return '32%';
      }
    },
    
    // 保存到浏览记录
    saveToHistory() {
      if (!this.newsData.id) return;
      
      // 获取已有历史记录
      let history = uni.getStorageSync('newsHistory') || [];
      
      // 构建记录数据
      const historyItem = {
        id: this.newsData.id,
        title: this.newsData.title,
        type: this.newsData.type,
        source: this.newsData.source,
        image: this.newsData.images && this.newsData.images.length > 0 ? this.newsData.images[0] : '',
        time: new Date().toISOString()
      };
      
      // 去重（如果已存在则移除旧记录）
      history = history.filter(item => item.id !== this.newsData.id);
      
      // 添加新记录到头部
      history.unshift(historyItem);
      
      // 限制最多保存100条记录
      if (history.length > 100) {
        history = history.slice(0, 100);
      }
      
      // 保存到本地存储
      uni.setStorageSync('newsHistory', history);
    },
    
    // 评论相关功能
    submitComment() {
      const content = this.newCommentContent.trim();
      if (!content) return;
	  
	  // 模拟提交评论
	  const newComment = {
	    id: this.newsData.id,
		newsId:this.newsData.id,
		userId:this.userInfo.appUserId,
	    user: {
	      id: this.userInfo.appUserId,
	      name: '我',
	      avatar: this.userInfo.avatar?this.userInfo.avatar:'/static/carbon-fiber.png'
	    },
	    content: content,
	    likeCount: 0,
	    isLiked: false,
	    time: new Date().toISOString(),
	    replies: [],
	    showReplyInput: false,
	    replyContent: '',
	    replyingTo: null
	  };
      this.$request('api/v1/addComment', 'POST',newComment).then(result => {
      	if (result.code==200) {
      	  // 显示成功提示
      	  uni.showToast({
      	    title: '评论成功',
      	    icon: 'none'
      	  });
      	} else {
      	  uni.showToast({ title: '评论失败', icon: 'none' });
      	}	  
      	
      });
	  
	  
      
      
      // 添加到评论列表头部
      this.comments.unshift(newComment);
      
      // 清空输入框
      this.newCommentContent = '';
      
      // 更新评论数
      this.newsData.commentCount++;
      
      
    },
    
    // 评论点赞
    handleCommentLike(comment) {
		this.$request(`api/v1/${comment.id}/like?userId=${this.userInfo.appUserId}`, 'POST').then(result => {
			if (result.code==200) {
			  if (comment.isLiked) {
			    comment.likeCount--;
			  } else {
			    comment.likeCount++;
			  }
			  comment.isLiked = !comment.isLiked;
			}   
			
		});
      
    },
    
    // 回复点赞
    handleReplyLike(comment, reply) {
	  this.$request(`api/v1/replies/${reply.id}/like?userId=${this.userInfo.appUserId}`, 'POST').then(result => {
	  	if (result.code==200) {
	  	  if (reply.isLiked) {
	  	    reply.likeCount--;
	  	  } else {
	  	    reply.likeCount++;
	  	  }
	  	  reply.isLiked = !reply.isLiked;
	  	}   
	  	
	  });
      
    },
    
    // 回复评论
    replyToComment(comment) {
      // 关闭其他评论的回复框
      this.comments.forEach(c => {
        if (c.id !== comment.id) {
          c.showReplyInput = false;
        }
      });
      
      // 打开当前评论的回复框
      comment.showReplyInput = !comment.showReplyInput;
      comment.replyContent = '';
      comment.replyingTo = null;
      
      // 滚动到回复框
      this.$nextTick(() => {
        // const replyInput = uni.createSelectorQuery().select(`.reply-input-section input`);
        // replyInput.focus();
		 // 使用in(this)确保在当前组件内查询
		     const query = uni.createSelectorQuery().in(this);
		     // 精确选择当前评论的回复输入框（避免选中其他评论的输入框）
		     query.select(`.comment-item:nth-child(${this.comments.indexOf(comment) + 1}) .reply-input`)
		       .fields({ node: true }, res => {
		         if (res && res.node) {
		           // 获取输入框DOM节点并聚焦
		           res.node.focus();
		         }
		       })
		       .exec(); // 执行查询
      });
    },
    
    // 回复回复
    replyToReply(comment, reply) {
      // 关闭其他评论的回复框
      this.comments.forEach(c => {
        if (c.id !== comment.id) {
          c.showReplyInput = false;
        }
      });
      
      // 打开当前评论的回复框
      comment.showReplyInput = true;
      comment.replyContent = '';
      comment.replyingTo = reply.user;
      
      // 滚动到回复框
      this.$nextTick(() => {
        const replyInput = uni.createSelectorQuery().select(`.reply-input-section input`);
        replyInput.focus();
      });
    },
    
    // 提交回复
    submitReply(comment) {
      const content = comment.replyContent.trim();
      if (!content) return;
      
      // 模拟提交回复
      // const newReply = {
      //   id: `reply-new-${Date.now()}`,
      //   user: {
      //     id: 'current-user',
      //     name: '我',
      //     avatar: '/static/carbon-fiber.png'
      //   },
      //   toUser: comment.replyingTo || null,
      //   content: content,
      //   likeCount: 0,
      //   isLiked: false,
      //   time: new Date().toISOString()
      // };
	  const newReply = {
	    id: comment.id,
	    user: {
	      id: this.userInfo.appUserId,
	      name: '我',
	      avatar: this.userInfo.avatar?this.userInfo.avatar:'/static/carbon-fiber.png'
	    },
	    toUser: comment.replyingTo || null,
	    content: content,
	    likeCount: 0,
	    isLiked: false,
	    time: new Date().toISOString()
	  };
	  
	  this.$request('api/v1/'+comment.id+'/replies', 'POST',newReply).then(result => {
	  	if (result.code==200) {
	  	  // 显示成功提示
	  	  uni.showToast({
	  	    title: '回复成功',
	  	    icon: 'none'
	  	  });
		  // 添加到回复列表
		  if (!comment.replies) {
		    comment.replies = [];
		  }
		  comment.replies.push(newReply);
	  	} else {
	  	  uni.showToast({ title: '回复失败', icon: 'none' });
	  	}	  
	  	
	  });
      
     
      
      // 清空回复框并关闭
      comment.replyContent = '';
      comment.showReplyInput = false;
      comment.replyingTo = null;
      
      // 更新评论数
      this.newsData.commentCount++;
      
      // 显示成功提示
      uni.showToast({
        title: '回复成功',
        icon: 'none'
      });
    },
    
    // 取消回复
    cancelReply(comment) {
      // 如果回复内容为空，则关闭回复框
      if (!comment.replyContent.trim()) {
        comment.showReplyInput = false;
        comment.replyingTo = null;
      }
    },
    
    // 切换评论排序方式
    toggleSort() {
      this.sortByHot = !this.sortByHot;
    },
    
    // 格式化评论时间
    formatCommentTime(timeStr) {
      try {
        const commentTime = new Date(timeStr);
        const now = new Date();
        const diffMs = now - commentTime;
        const diffMin = Math.floor(diffMs / 60000);
        const diffHour = Math.floor(diffMin / 60);
        const diffDay = Math.floor(diffHour / 24);
        
        if (diffMin < 1) {
          return '刚刚';
        } else if (diffMin < 60) {
          return `${diffMin}分钟前`;
        } else if (diffHour < 24) {
          return `${diffHour}小时前`;
        } else if (diffDay < 30) {
          return `${diffDay}天前`;
        } else {
          const month = commentTime.getMonth() + 1;
          const day = commentTime.getDate();
          return `${month}月${day}日`;
        }
      } catch (e) {
        return '未知时间';
      }
    },
    
    // 滚动到评论区
    // scrollToComments() {
    //   this.$refs.commentsRef.scrollIntoView({ behavior: 'smooth' });
      
    //   // 延迟聚焦评论框
    //   setTimeout(() => {
    //     this.focusCommentInput();
    //   }, 500);
    // },
    
    // 聚焦评论输入框
    focusCommentInput() {
      const input = uni.createSelectorQuery().select('.comment-input-section input, .bottom-bar .comment-input');
      input.focus();
    },
    
    // 隐藏底部操作栏
    hideBottomBar() {
      this.bottomBarHidden = true;
    },
    
    // 显示底部操作栏
    showBottomBar() {
      this.bottomBarHidden = false;
    },
    
    // 加载更多评论
    loadMoreComments() {
      if (this.hasMoreComments && !this.showLoadMoreComments) {
        this.commentPage++;
        this.fetchComments();
      }
    },
	targetIsLiked(targetId,targetType){
		if (!this.userInfo) return;
		this.$request(`api/v1/${targetId}/targetIsLiked?userId=${this.userInfo.appUserId}&targetType=${targetType}`, 'POST').then(result => {
			if (result.code==200) {
			  this.isLiked = result.data
			}   
			
		});
	},
	newsView(){
		setTimeout(() => {
			this.$request(`api/v1/${this.newsId}/view`, 'POST').then(result => {
				if (result.code==200) {
				  this.newsData.views++;
				}   
				
			});
		},2000)
			
		
	},
	isAttention(){
		if (!this.userInfo || !this.authorId) return;
		const param = {'fansId':this.userInfo.appUserId,'concernId':this.authorId}
		this.$request(`api/v1/isAttention`, 'POST',param).then(result => {
			if (result.code==200) {
			  this.newsData.author.isFollowed = result.data
			  console.log(this.newsData.author.isFollowed)
			}   
			
		});
	}

  }
};
</script>

<style lang="scss" scoped>
.detail-page {
  background-color: #f5f5f7;
  min-height: 100vh;
  padding-bottom: 120rpx; // 为底部操作栏预留空间
}

// 导航栏样式
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;

  .back-btn, .operate-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .title {
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
    flex: 1;
    text-align: center;
  }
}

// 文章详情样式
.article-detail {
  background-color: #fff;
  padding: 30rpx 30rpx 50rpx;
  margin-bottom: 20rpx;

  .article-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    line-height: 1.5;
    margin-bottom: 25rpx;
  }

  .article-info {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #999;
    margin-bottom: 25rpx;
    flex-wrap: wrap;

    .article-source {
      margin-right: 20rpx;
    }

    .article-time {
      margin-right: 20rpx;
    }
  }

  .article-images {
    margin-bottom: 30rpx;

    .article-img {
      width: 100%;
      border-radius: 12rpx;
      margin-bottom: 15rpx;
    }
  }

  .article-content {
    font-size: 30rpx;
    color: #333;
    line-height: 2;
    margin-bottom: 40rpx;

    rich-text {
      line-height: 2;
    }

    p {
      margin-bottom: 20rpx;
    }
  }

  .author-info {
    display: flex;
    align-items: center;
    padding-top: 20rpx;
    border-top: 1px solid #f5f5f5;

    .author-avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }

    .author-detail {
      flex: 1;

      .author-name {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        display: block;
        margin-bottom: 5rpx;
      }

      .author-desc {
        font-size: 24rpx;
        color: #999;
      }
    }

    .follow-btn {
      width: 120rpx;
      height: 50rpx;
      line-height: 50rpx;
      text-align: center;
      border-radius: 25rpx;
      font-size: 24rpx;
      background-color: #f5f5f5;
      color: #666;
      border: none;

      &.followed {
        background-color: #1677FF;
        color: #fff;
		width: 150rpx;
      }
    }
  }
}

// 微头条详情样式
.micro-detail {
  background-color: #fff;
  padding: 25rpx 30rpx;
  margin-bottom: 20rpx;

  .micro-author {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .micro-avatar {
      width: 70rpx;
      height: 70rpx;
      border-radius: 50%;
      margin-right: 15rpx;
    }

    .micro-author-info {
      flex: 1;

      .micro-author-name {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        display: block;
        margin-bottom: 5rpx;
      }

      .micro-publish-time {
        font-size: 22rpx;
        color: #999;
      }
    }

    .follow-btn {
      width: 110rpx;
      height: 45rpx;
      line-height: 45rpx;
      text-align: center;
      border-radius: 22rpx;
      font-size: 22rpx;
      background-color: #f5f5f5;
      color: #666;
      border: none;

      &.followed {
        background-color: #1677FF;
        color: #fff;
      }
    }
  }

  .micro-content {
    margin-bottom: 20rpx;

    .micro-text {
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
      display: block;
      margin-bottom: 20rpx;
    }

    .micro-images {
      margin-bottom: 10rpx;
    }

    .image-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 10rpx;
    }

    .micro-img {
      border-radius: 8rpx;
      aspect-ratio: 1/1;
      object-fit: cover;
    }
  }

  .micro-stats {
    display: flex;
    align-items: center;
    font-size: 22rpx;
    color: #999;
    padding-top: 10rpx;

    .publish-place {
      margin-right: 20rpx;
    }
  }
}

// 互动工具栏
.interactive-bar {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 15rpx 0;
  border-top: 1px solid #f5f5f5;
  border-bottom: 1px solid #f5f5f5;

  .interactive-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .interactive-icon {
      margin-bottom: 5rpx;
    }

    .interactive-text {
      font-size: 22rpx;
      color: #999;
    }

    .liked {
      color: #ff4d4f;
    }

    .collected {
      color: #ffb800;
    }

    .comment-count {
      font-size: 20rpx;
      color: #1677FF;
      margin-left: 5rpx;
    }
  }
}

// 评论区样式
.comments-section {
  background-color: #fff;
  padding: 25rpx 30rpx;
  margin-bottom: 120rpx;

  .comments-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25rpx;

    .comments-title {
      font-size: 25rpx;
      font-weight: 500;
      color: #333;
	  flex-grow: 1;
	  overflow: hidden;
	  text-overflow: ellipsis;
	  white-space: nowrap;
    }

    .sort-text {
      font-size: 24rpx;
      color: #666;
      display: flex;
      align-items: center;
    }
  }

  // 评论输入区
  .comment-input-section {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    padding-bottom: 20rpx;
    border-bottom: 1px solid #f5f5f5;

    .user-avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      margin-right: 15rpx;
    }

    .comment-input {
      flex: 1;
      background-color: #f5f5f5;
      border-radius: 30rpx;
      padding: 15rpx 20rpx;
      font-size: 26rpx;
      color: #333;
      height: 60rpx;
      line-height: 30rpx;
    }

    .send-btn {
      width: 80rpx;
      height: 50rpx;
      line-height: 50rpx;
      text-align: center;
      background-color: #1677FF;
      color: #fff;
      border: none;
      border-radius: 25rpx;
      font-size: 24rpx;
      margin-left: 15rpx;

      &:disabled {
        background-color: #ccc;
        opacity: 0.7;
      }
    }
  }

  // 评论列表
  .comments-list {
    margin-bottom: 20rpx;
  }

  .comment-item {
    display: flex;
    margin-bottom: 30rpx;

    .comment-avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      margin-right: 15rpx;
      flex-shrink: 0;
    }

    .comment-content {
      flex: 1;

      .comment-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8rpx;

        .comment-username {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
        }

        .comment-time {
          font-size: 22rpx;
          color: #999;
        }
      }

      .comment-text {
        font-size: 26rpx;
        color: #333;
        line-height: 1.5;
        margin-bottom: 10rpx;
        display: block;
      }

      .comment-actions {
        display: flex;
        margin-bottom: 15rpx;

        .action-item {
          display: flex;
          align-items: center;
          margin-right: 25rpx;
          font-size: 22rpx;
          color: #999;

          uni-icons {
            margin-right: 5rpx;
          }
        }
      }

      // 回复列表
      .replies-list {
        background-color: #f9f9f9;
        border-radius: 10rpx;
        padding: 15rpx;
        margin-bottom: 15rpx;

        .reply-item {
          margin-bottom: 15rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .reply-username {
            font-size: 24rpx;
            color: #333;
            font-weight: 500;
          }

          .reply-to {
            font-size: 24rpx;
            color: #999;
          }

          .reply-content {
            font-size: 24rpx;
            color: #333;
          }

          .reply-actions {
            display: flex;
            margin-top: 5rpx;

            .reply-action {
              display: flex;
              align-items: center;
              margin-right: 20rpx;
              font-size: 20rpx;
              color: #999;

              uni-icons {
                margin-right: 3rpx;
              }
            }
          }
        }
      }

      // 回复输入框
      .reply-input-section {
        display: flex;
        align-items: center;
        margin-top: 15rpx;

        .reply-input {
          flex: 1;
          background-color: #f5f5f5;
          border-radius: 25rpx;
          padding: 12rpx 18rpx;
          font-size: 24rpx;
          color: #333;
          height: 50rpx;
          line-height: 26rpx;
        }

        .reply-send-btn {
          width: 70rpx;
          height: 45rpx;
          line-height: 45rpx;
          text-align: center;
          background-color: #1677FF;
          color: #fff;
          border: none;
          border-radius: 22rpx;
          font-size: 22rpx;
          margin-left: 10rpx;
        }
      }
    }
  }

  // 加载更多评论
  .load-more-comments {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx 0;

    .load-more-text {
      font-size: 24rpx;
      color: #999;
      margin-left: 10rpx;
    }
  }
}

// 底部操作栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  height: 100rpx;
  z-index: 10;
  transition: transform 0.3s ease;

  &.hidden {
    transform: translateY(100%);
  }

  .comment-btn {
    flex: 3;
    height: 70rpx;
    margin: 15rpx 15rpx 15rpx 20rpx;
    background-color: #f5f5f5;
    border-radius: 35rpx;
    border: none;
    display: flex;
    align-items: center;
    padding-left: 25rpx;

    .btn-icon {
      margin-right: 10rpx;
    }

    .comment-input {
      flex: 1;
      background: transparent;
      border: none;
      outline: none;
      font-size: 26rpx;
      color: #333;
      height: 100%;
    }
  }

  .share-btn {
    flex: 1;
    height: 70rpx;
    margin: 15rpx 20rpx 15rpx 0;
    background-color: #1677FF;
    color: #fff;
    border-radius: 35rpx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
  }

  .btn-icon {
    margin-right: 10rpx;
  }
}
</style>
